//
//  CollectionViewLayout.m
//  test
//
//  Created by huichen on 2018/6/4.
//  Copyright © 2018年 huichen. All rights reserved.
//

#import "CollectionViewLayout.h"


@interface CollectionViewLayout()

@property (nonatomic, strong) NSMutableArray *itemAttributes;


@property (nonatomic, assign) CGFloat originSuperViewHeight;
/**
 *  存放每行宽度字典
 */
@property (nonatomic, strong) NSMutableDictionary *widthOfRowDic;

/**
 *  存放所有item的attrubutes属性
 */
@property (nonatomic, strong) NSMutableArray *itemsArray;

/**
 *  计算每个item宽度的block，必须实现
 */
@property (nonatomic, copy) WidthBlock block;

@end

@implementation CollectionViewLayout

@dynamic sectionInset;

- (id)initWithCollectionViewHeight:(CGFloat)height
{
    if (self = [super init]) {
        
        self.rowNumber = 2;
        self.currentowNumber = 2;
        self.rowSpacing = 10.0f;
        self.lineSpacing = 10.0f;
        self.sectionInset = UIEdgeInsetsMake(10,10,10,10);
        _widthOfRowDic = [NSMutableDictionary dictionary];
        _itemsArray = [NSMutableArray array];
        _originSuperViewHeight = height;
    }
    
    return self;
}

/**
 *  准备好布局
 */
- (void)prepareLayout
{
    [super prepareLayout];
    
    [self.itemsArray removeAllObjects];
    [self.widthOfRowDic removeAllObjects];
    
     NSInteger count = [self.collectionView numberOfItemsInSection:0];
    //初始化好每行的宽度
    for (NSInteger i = 0; i < self.rowNumber ; i++) {
        
        [_widthOfRowDic setObject:@(self.sectionInset.left) forKey:[NSString stringWithFormat:@"%ld",i]];
        
    }
    //得到每个item的属性值进行存储
    for (NSInteger i = 0 ; i < count; i ++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [_itemsArray addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
}

/**
 *  设置可滚动区域范围
 *
 *  @return 可滚动区域的size
 */
- (CGSize)collectionViewContentSize {
    
    __block NSString *maxWidthLine = @"0";
    [_widthOfRowDic enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *obj, BOOL *stop) {
        
        if ([self->_widthOfRowDic[maxWidthLine] floatValue] < [obj floatValue] ) {
            maxWidthLine = key;
        }
    }];
    return CGSizeMake([_widthOfRowDic[maxWidthLine] floatValue] + self.sectionInset.right,self.collectionView.bounds.size.height);
}

/**
 *
 *  @return 返回视图框内item的属性，可以直接返回所有item属性
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    return _itemsArray;
}

/**
 *  计算indexPath下item的属性的方法
 *
 *  @return item的属性
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //通过indexPath创建一个item属性attr
    UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
     //计算item高
    CGFloat itemH = (_originSuperViewHeight - (self.sectionInset.top + self.sectionInset.bottom) - (self.rowNumber - 1) * self.rowSpacing) / self.rowNumber;
    
    //计算item宽
    CGFloat itemW = 0.0;
    if (self.block != nil) {
    
        itemW = self.block(indexPath,itemH);
    } else {
    
        NSAssert(itemW != 0,@"Please implement computeIndexCellHeightWithWidthBlock Method");
    }
    
    //计算item的frame
    CGRect frame;
    frame.size = CGSizeMake(itemW, itemH);
    
    // 计算当前item所在位置
    NSString *widthOfRow = [NSString stringWithFormat:@"%ld",indexPath.row%self.rowNumber];
    frame.origin = CGPointMake([_widthOfRowDic[widthOfRow] floatValue], self.sectionInset.top + widthOfRow.intValue * (itemH + self.rowSpacing));

    // 更新行宽度
    _widthOfRowDic[widthOfRow] = @(frame.size.width + self.lineSpacing + [_widthOfRowDic[widthOfRow] floatValue]);
    attr.frame = frame;
    NSLog(@"++++++++++++%@",NSStringFromCGRect(frame));
    [self updteSuperViewFrame];
    return attr;
     
}

- (void)updteSuperViewFrame{

    if (self.currentowNumber < self.rowNumber){
        
        NSInteger newNum = self.currentowNumber;
        
        CGFloat rowHeight = (_originSuperViewHeight - (self.sectionInset.top + self.sectionInset.bottom) - (self.rowNumber - 1) * self.rowSpacing) / self.rowNumber;

       CGFloat height = self.sectionInset.top + self.sectionInset.bottom + newNum * rowHeight + (newNum - 1) *self.rowSpacing;
       if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayoutChangeSuperViewHeight:)]) {
            [self.delegate collectionViewLayoutChangeSuperViewHeight:height];
        }
    } else {
    
        if (_originSuperViewHeight != self.collectionView.frame.size.height) {
              if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayoutChangeSuperViewHeight:)]) {
                [self.delegate collectionViewLayoutChangeSuperViewHeight:_originSuperViewHeight];
            }
        }
    }
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return NO;
}


- (void)computeIndexCellHeightWithWidthBlock:(CGFloat(^)(NSIndexPath *indexPath , CGFloat height))block{
   
    if (self.block != block) {

        self.block = block;
    }
}

@end
